<?php

namespace App\Admin\Controllers\Bj;

use App\Admin\Actions\Grid\Batch\SwtBjMachine\SyncMachine;
use App\Admin\Actions\Grid\Row\SwtBjMachine\MachineDetail;
use App\Admin\Actions\Grid\Row\SwtBjMachine\MachineOpen;
use App\Admin\Actions\Grid\Row\SwtBjMachine\MachineRegister;
use App\Admin\Actions\Grid\Row\SwtBjMachine\MachineRestart;
use App\Admin\Actions\Grid\Row\SwtBjMachine\MachineSetting;
use App\Admin\Actions\Grid\Tools\SwtBjMachine\ImportMachine;
use App\Admin\Logic\Bj\BjMachineLogic;
use App\Admin\Logic\Ty\TyMachineLogic;
use App\Models\SwtBjCabinet;
use App\Models\SwtBjMachine;
use App\Services\BaoJianService;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Show;
use Dcat\Admin\Http\Controllers\AdminController;
use Dcat\Admin\Widgets\Table;
use Illuminate\Validation\Rule;

class SwtBjMachineController extends AdminController
{
    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Grid::make(SwtBjMachine::with('cabinet'), function (Grid $grid) {
            $grid->model()->orderBy('id', 'desc');
            $grid->column('id')->sortable();
            $grid->column('machine_id') -> display( function ($value) {
                return $value ? : '<span class="text-danger">暂未同步</span>';
            });
            $grid->column('imei')->copyable();
            $grid->column('machine_code');
            $grid->column('machine_name');
            $grid->column('device_code');
            $grid->column('power_status')->using([1=>'通电', 2=>'断电'])->label([1=>'success',2=>'warning']);
            $grid->column('sale_status')->using([1=>'启用', 2=>'禁用'])->label([1=>'success',2=>'warning']);
            $grid->column('online_status')->using([1=>'在线', 2=>'离线'])->label([1=>'success',2=>'warning']);
            $grid->column('is_register','拓元注册')->using([0=>'未注册',1=>'申请中',2=>'成功',3=>'失败', 4=>'禁用'])->label([0=>'warning',1=>'info',2=>'success',3=>'danger',4=>'danger']);
            $grid->column('cabinet','柜门')->display('查看')->expand(function () {
                $cabinet_list = [];
                foreach($this->cabinet as $v) {
                    $cabinet_list[] = [
                        'cabinet_no'      => $v['cabinet_no'],
                        'camera_no'       => $v['camera_no'],
                        'lock_status'     => $v['lock_status'] == 1 ? '开锁' : '关锁',
                        'resolution'      => $v['resolution'],
                        'frame_rate'      => $v['frame_rate'].'帧',
                        'exposure'        => $v['exposure'],
                        'bit_stream'      => $v['bit_stream'],
                    ];
                }
                return new Table(['柜门','摄像头','锁状态','分辨率','帧率','曝光','码流'], $cabinet_list);
            });
            $grid->column('last_online_time') -> display( function ($value) {
                return $value ?? '-';
            });
            $grid->column('updated_at')->sortable();

            $grid->actions(function (Grid\Displayers\Actions $actions) {
                $actions->append(new MachineSetting());
                $actions->append(new MachineDetail());
                $actions->append(new MachineRestart());
                $actions->append(new MachineOpen());
                if(!in_array($this->is_register,[1,2])) {
                    $actions->append(new MachineRegister());
                }
                if(!$this->machine_id) {
                    $actions->disableDelete(false);
                }
            });

            $grid->selector(function (Grid\Tools\Selector $selector) {
                $selector->selectOne('machine_id', '是否关联', [
                    '未关联',
                    '已关联',
                ], function ($query, $value) {
                    if($value) {
                        $query->whereNotNull('machine_id');
                    } else {
                        $query->whereNull('machine_id');
                    }
                });
            });

            $grid->disableCreateButton(false);

            $grid->disableRowSelector(false);

            $grid->rowSelector()->disable(function ($row) {
                return $row->machine_id != null && $row->is_register == 2;
            });

            $grid->rowSelector()->titleColumn('id');

            $grid->batchActions(function (Grid\Tools\BatchActions $batch) {
                $batch->add(new SyncMachine());
                $batch->disableDelete();
            });

            $grid->tools(function (Grid\Tools $tools)  {
                $tools->append(new ImportMachine());
            });

            $grid->quickSearch('machine_code');
        });
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     *
     * @return Show
     */
    protected function detail($id)
    {
        return Show::make($id, new SwtBjMachine(), function (Show $show) {
            $show->field('id');
            $show->field('machine_id');
            $show->field('machine_code');
            $show->field('machine_name');
            $show->field('address');
            $show->field('device_code');
            $show->field('system_volume');
            $show->field('media_volume');
            $show->field('online_status');
            $show->field('last_online_time');
            $show->field('created_at');
            $show->field('updated_at');
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Form::make(new SwtBjMachine(), function (Form $form) {
            $form->text('imei')->required()->rules(
                ['required', Rule::unique('swt_bj_machine') -> whereNull('deleted_at'), 'size:15'],
                ['unique' => 'IMEI已存在', 'size' => '请输入15位IMEI号']
            );
            $form->hidden('machine_code');
            $form->hidden('device_code');
            $form->text('machine_name')->required();
            $form->text('address');

            $form->saving(function (Form $form) {
                if($form->isCreating()) {
                    $machine_code = SwtBjMachine::orderBy('id', 'desc')->value('machine_code');

                    $form -> machine_code = $machine_code ? $machine_code + 1 : '90000001';

                    $res = BaoJianService::machineRegister( $form->imei, $form -> machine_code);

                    $form -> device_code = $res['deviceCode'];
                }
            });

            $form->saved(function (Form $form) {
                $id = $form -> getKey();

                if($form->isCreating()) {
                    if($id) {
                        $params = [
                            'id'           => $id,
                            'imei'         => $form->input('imei'),
                            'machine_code' => $form->input('machine_code'),
                            'device_code'  => $form->input('device_code'),
                            'machine_name' => $form->input('machine_name'),
                            'address'      => $form->input('address')
                        ];
                        //拓元设备登记
                        TyMachineLogic::asyncMachine($params);
                        //添加设备柜门信息
                        $data = [
                            [
                                'bj_machine_id' => $id,
                                'cabinet_no'    => 1,
                                'camera_no'     => 1,
                                'created_at'    => date('Y-m-d H:i:s', time())
                            ],
                            [
                                'bj_machine_id' => $id,
                                'cabinet_no'    => 1,
                                'camera_no'     => 2,
                                'created_at'    => date('Y-m-d H:i:s', time())
                            ]
                        ];
                        SwtBjCabinet::insert($data);
                        //查询设备状态
                        BjMachineLogic::refreshMachineInfo($form->input('device_code'));
                    }
                }
            });
        });
    }
}
